from time import time, sleep

from config import args
from logger import logger


class Timer:

    def __init__(self, timer_name: str = 'default', **kwargs):

        self.event = kwargs.get('event', 'build a timer')
        self.counter = 0
        self.timer_name = timer_name
        logger.logger.info(f'a timer [{self.timer_name}] is built')
        self.time = time()

    def clock(self, event: str = '', verbose=True):
        interval = time() - self.time
        self.counter += 1
        if not event:
            event = f'use clock {self.counter} times'
        if verbose:
            logger.logger.info(f'[timer {self.timer_name}]: {args.prefix}{interval:.2f}{args.suffix} secs '
                               f'between [{self.event}] and [{event}]')
        self.event = event
        self.time = time()

        return interval


class TimeAccumulator(Timer):

    def __init__(self, accumulator_name: str = 'default', **kwargs):
        super().__init__(accumulator_name, event='build a time accumulator')
        self.accumulator = {}  # {event_id: [Timer, accumulated time]}

    def set_start(self, event_id):

        if self.accumulator.get(event_id, None) is None:
            self.accumulator[event_id] = [Timer(str(event_id), event=event_id), 0]
        else:
            self.accumulator[event_id][0].clock(verbose=False)

    def set_end(self, event_id):
        assert self.accumulator.get(event_id, None) is not None
        self.accumulator[event_id][1] += self.accumulator[event_id][0].clock(verbose=False)

    def get_accumulated_time(self, event_id):
        assert self.accumulator.get(event_id, None) is not None
        return self.accumulator[event_id][1]


if __name__ == '__main__':
    t = TimeAccumulator()
    for i in range(10):
        t.set_start(1)
        sleep(0.1)
        t.set_end(1)
        sleep(0.1)
    print(t.get_accumulated_time(1))
    # sleep(1)
    # t.clock()
    # sleep(1)
    # t.clock()
